/*
@Author   : Uyynot
@Email    : uyynot@qq.com
@Time     : 2024/1/12 18:44
@File     : signup_controller.go
@Project  : gohub
@Desc     :
*/
package auth

import (
	"github.com/gin-gonic/gin"
	v1 "gohub/app/http/controllers/api/v1"
	"gohub/app/models/user"
	"gohub/app/requests"
	"gohub/pkg/jwt"
	"gohub/pkg/response"
)

// SignupController 注册控制器
type SignupController struct {
	v1.BaseAPIController
}

// IsPhoneExist 手机是否已存在
func (s *SignupController) IsPhoneExist(c *gin.Context) {
	//初始化请求对象
	request := requests.SignUpPhoneExistRequest{}
	//请求校验
	if ok := requests.Validate(c, &request, requests.ValidateSignupPhoneExist); !ok {
		return
	}

	//查询数据库手机是否已存在
	response.JSON(c, gin.H{
		"exist": user.IsPhoneExist(request.Phone),
	})
}

// IsEmailExist 邮箱是否已存在
func (s *SignupController) IsEmailExist(c *gin.Context) {

	//初始化请求对象
	request := requests.SignIUpEmailExistRequest{}
	//请求校验
	if ok := requests.Validate(c, &request, requests.ValidateSignUpEmailExist); !ok {
		return
	}

	//数据库查询邮箱
	response.JSON(c, gin.H{
		"exist": user.IsEmailExist(request.Email),
	})

}

// SignupUsingPhone 使用手机和验证码注册
func (s *SignupController) SignupUsingPhone(c *gin.Context) {
	//验证表单
	request := requests.SignupUsingPhoneRequest{}
	if ok := requests.Validate(c, &request, requests.SignupUsingPhone); !ok {
		return
	}
	//验证成功，创建数据
	_user := user.User{
		Name:     request.Name,
		Phone:    request.Phone,
		Password: request.Password,
	}
	_user.Create()

	if _user.ID > 0 {
		//获取token
		token := jwt.NewJWT().IssueToken(_user.GetStringID(), _user.Name)
		response.CreatedJSON(c, gin.H{"token": token, "data": _user})
	} else {
		response.Abort500(c, "创建用户失败，请稍后尝试")
	}
}

// SignupUsingEmail 使用邮箱和验证码注册
func (s *SignupController) SignupUsingEmail(c *gin.Context) {
	//验证表单
	request := requests.SignupUsingEmailRequest{}
	if ok := requests.Validate(c, &request, requests.SignupUsingEmail); !ok {
		return
	}
	//验证成功，创建数据
	_user := user.User{
		Name:     request.Name,
		Email:    request.Email,
		Password: request.Password,
	}
	_user.Create()

	if _user.ID > 0 {
		token := jwt.NewJWT().IssueToken(_user.GetStringID(), _user.Name)
		response.CreatedJSON(c, gin.H{"token": token, "data": _user})
	} else {
		response.Abort500(c, "创建用户失败，请稍后重试")
	}
}
